package com.ihome.framework.core.mq;

import java.io.UnsupportedEncodingException;

import org.apache.commons.lang3.StringUtils;
import org.springframework.util.Assert;

import com.netease.cloud.nqs.client.Message;
import com.netease.cloud.nqs.client.consumer.MessageHandler;

public class MQCommonTester {

    public static void main(String[] args) {
        String host = System.getProperty("host");
        if (StringUtils.isBlank(host)) {
            System.out.println("java -Dhost=mq.wjjr.cc -Dfor=producer -Dusername=appops -Dpassword=appops -Dexchange=ap -Dqueue=xxx -jar yyy.jar");
            System.out.println("java -Dhost=mq.wjjr.cc -Dfor=consumer -Dusername=appops -Dpassword=appops -Dexchange=ap -Dqueue=xxx -jar yyy.jar");
            Assert.notNull(host);
        }
        String fors = System.getProperty("for");
        Assert.notNull(fors);
        if (!"producer".equals(fors) && !"consumer".equals(fors)) {
            throw new RuntimeException("for must be producer or consumer");
        }
        String username = System.getProperty("username");
        String password = System.getProperty("password");
        String exchange = System.getProperty("exchange");
        String queue = System.getProperty("queue");
        Assert.notNull(username);
        Assert.notNull(password);
        Assert.notNull(exchange);
        Assert.notNull(queue);

        MQConfig mqConfig = new MQConfig();
        mqConfig.setHost(host);
        mqConfig.setPort(5672);
        mqConfig.setUsername(username);
        mqConfig.setPassword(password);
        mqConfig.setExchange(exchange);

        if("producer".equals(fors)) {
            final MQProducerConfig mpc = new MQProducerConfig();
            mpc.setRequireConfirm(true);
            mpc.setConfirmTimeout(3000);

            final MQProducer producer = new MQProducer(mqConfig, mpc);
            producer.init();
            for (int i = 0; i < 100; i++) {
                System.out.println("send message :" + i);
                producer.sendMessage("justtest" + i, queue);
                try {
                    Thread.sleep(10000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }   
        }
        if("consumer".equals(fors)) {
            MQConsumerConfig mqcc = new MQConsumerConfig();
            mqcc.setPrefetchCount(100);

            MQConsumer mqc = new MQConsumer(mqConfig, mqcc);
            mqc.init();
            mqc.consumeMessage(queue, new MessageHandler() {
                @Override
                public boolean handle(Message mess) {
                    try {
                        System.out.println(new String(mess.getBody(), "UTF-8"));
                    } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                    }
                    return true;
                }
            });
        }
    }
}
